# -*- coding: utf-8 -*-
# requests 第三方库使用 pip install requests
import requests
import io
import sys
sys.stdout = io.TextIOWrapper(sys.stdout.buffer,encoding='utf-8')

r = requests.get('https://www.douban.com/')
print(r.status_code)
print(r.text)

# 如果带参数，传入一个dick作为params参数
r = requests.get('https://www.douban.com/search', params={'q': 'python', 'cat': '1001'})
print(r.url)
print(r.encoding)

r = requests.get('https://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20weather.forecast%20where%20woeid%20%3D%202151330&format=json')
print(r.json())

# 需要传入HTTP Header时，传入一个dict作为headers参数
r = requests.get('https://www.douban.com/', headers={'User-Agent': 'Mozilla/5.0 (iPhone; CPU iPhone OS 11_0 like Mac OS X) AppleWebKit'})
print(r.text)

# POST 请求 requests默认使用application/x-www-form-urlencoded对POST数据编码
r = requests.post('https://accounts.douban.com/login', data={'form_email': 'abc@example.com', 'form_password': '123456'})
print(r.text)

# 如果要传递JSON数据，可以直接传入json参数
params = {'key':'value'}
# 内部自动序列化
r = requests.post('https://accounts.douban.com/login',json=params)
print(r.text)

# 上传文件
upload_files = {'file':open('blur.jpg','rb')}
r = requests.post('https://www.douban.com/',files=upload_files)

# 将PUT 或 DELETE方式请求资源，直接将post() 方法变换为put(),delete()等
print(r.headers)
print(r.headers['Content-Type'])
print(r.cookies)

# 传入cookies
cs = {'token':'12345','status':'working'}
r = requests.get('https://www.douban.com/', cookies=cs)
print(r.status_code)

# 指定超时，传入以秒为单位的timeout参数
r = requests.get('https://www.douban.com/', timeout=2.5)
print(r.status_code)
